import { useEffect, useState } from 'react';
import Qrcode from '@/pages/components/Qrcode';
import { check_scan, wechat_code } from '@/services/login/login';
import { Button, message } from 'antd';
import { Link, history } from 'umi';
import styles from './wechat.less';

export default function Page() {
  const [btn, setbtn] = useState(true)
  const [content, setcontent] = useState("刷 新")
  const [qrcodeurl, setqrcodeurl] = useState("")
  let ontimeer: any = null

  /**
   * 验证码检测
   * @param web_code 请求码
   */
  const check = async (web_code: string) => {
    const res = await check_scan({ web_code })
    if (res.code === 200) {
      // 扫码成功
      message.success("扫码成功")
      clearInterval(ontimeer)
      setTimeout(() => {
        history.push(`/user/choose/service?web_code=${web_code}`)
      }, 2000);
    } else {
      // 二维码超时
      if (res.code === 2001) {
        clearInterval(ontimeer)
        message.warn(res.message, 5)
        history.push('/user/login')
      }
      // 获取微信授权失败，请重新扫码授权
      if (res.code === 4000) {
        clearInterval(ontimeer)
        message.warn(res.message, 5)
        history.push('/user/login')
      }
      // 当前微信未绑定服务商账号
      if (res.code === 4001) {
        clearInterval(ontimeer)
        message.warn(res.message, 5)
        history.push('/user/login')
      }

    }
  }



  /**
   * 验证码倒计时
   * @param expires_time 过期时间
   * @param web_code 请求码
   */
  const countDown = (expires_time: number, web_code: string) => {
    setbtn(true)
    let timeout = expires_time * 1000
    const t = setInterval(() => {
      timeout -= 1000
      check(web_code)
      setcontent(`${(timeout / 1000).toString()}s 后过期`)
      if (timeout === 0) {
        clearInterval(t)
        setbtn(false)
        setcontent("刷 新")
      }
    }, 1000);
    ontimeer = t
  }


  /**
   * 获取二维码链接
   */
  const getcode = async () => {
    const res = await wechat_code({ scan_type: "login" })
    if (res.code === 200) {
      setqrcodeurl(res.data.qrcode_url)
      countDown(res.data.expires_time, res.data.web_code)
    } else {
      message.warn({ content: res.message })
    }
  }


  /**
   * 组件挂载
   */
  useEffect(() => {
    getcode()
    // Unmount
    return () => {
      window.console.log("Unmount");
      clearInterval(ontimeer)
    }
  }, [])

  return (
    <div className={styles.container}>
      <div className={styles.warp}>
        <Qrcode url={qrcodeurl} size={282} includeMargin={true} desc="微信登陆" />
        <div className={styles.qrcode_btn}>
          <Button type="primary" block disabled={btn} onClick={getcode} shape="round">{content}</Button>
        </div>
        <div style={{ color: "white", textAlign: "center", marginTop: "15px" }}>
          请使用微信扫描二维码登录
          <Link to="/service/login"> 使用账号登陆？</Link>
        </div>
      </div>
    </div>
  );
}
